<template>
  <j-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :destroyOnClose="true"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    
    <a-spin :spinning="confirmLoading">
      <a-tabs defaultActiveKey="1">
        <a-tab-pane tab="基本信息" key="1">
          <a-form :form="form">
            <a-row>
              <a-col :span="12">
                <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入客户名称" v-decorator="['customerName', validatorRules.customerName]" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="系统自动生成" v-decorator="['customerCode']" disabled/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag v-decorator="['customerType']" :trigger-change="true" dictCode="customer_type" placeholder="请选择客户类型" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="所属行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag v-decorator="['industry']" :trigger-change="true" dictCode="industry_type" placeholder="请选择所属行业" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag v-decorator="['customerSource']" :trigger-change="true" dictCode="customer_source" placeholder="请选择客户来源" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="信用等级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag v-decorator="['creditRating']" :trigger-change="true" dictCode="credit_rating" placeholder="请选择信用等级" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="跟进状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag v-decorator="['followUpStatus']" :trigger-change="true" dictCode="follow_up_status" placeholder="请选择跟进状态" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="跟进人员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-select-user-by-dep v-decorator="['followUpPerson']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="省市区" :labelCol="{span: 3}" :wrapperCol="{span: 19}">
                  <j-area-linkage type="cascader" v-decorator="['area']" :disabled="true"/>
                  <span v-if="!model.area && (model.provinceName || model.cityName || model.areaName)" style="margin-left: 10px; color: #666;">
                    {{ formatAreaText() }}
                  </span>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="详细地址" :labelCol="{span: 3}" :wrapperCol="{span: 19}">
                  <a-textarea placeholder="请输入详细地址" v-decorator="['address']" :rows="2" :disabled="true"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
        
        <a-tab-pane tab="联系信息" key="2">
          <a-form :form="form">
            <a-row>
              <a-col :span="12">
                <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入联系人" v-decorator="['contactPerson']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="职位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入职位" v-decorator="['position']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入联系电话" v-decorator="['contactPhone']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入手机号码" v-decorator="['mobilePhone']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="电子邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入电子邮箱" v-decorator="['email']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="QQ/微信" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入QQ或微信" v-decorator="['socialContact']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag v-decorator="['gender']" :trigger-change="true" dictCode="sex" placeholder="请选择性别" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker style="width: 100%" v-decorator="['birthday']" :disabled="true"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
        
        <a-tab-pane tab="财务信息" key="3">
          <a-form :form="form">
            <a-row>
              <a-col :span="12">
                <a-form-item label="开户银行" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入开户银行" v-decorator="['bankName']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="开户支行" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入开户支行" v-decorator="['bankBranch']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="银行账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入银行账号" v-decorator="['bankAccount']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="账户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入账户名称" v-decorator="['accountName']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="纳税人识别号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入纳税人识别号" v-decorator="['taxNumber']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="发票抬头" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入发票抬头" v-decorator="['invoiceTitle']" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="信用额度" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number style="width: 100%" placeholder="请输入信用额度" v-decorator="['creditLimit', {initialValue: 0}]" :min="0" :step="1000" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="账期(天)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number style="width: 100%" placeholder="请输入账期天数" v-decorator="['paymentTerm', {initialValue: 0}]" :min="0" :disabled="true"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
        
        <a-tab-pane tab="工程项目" key="4" forceRender>
          <div class="table-operator" style="margin-bottom: 15px;">
            <a-button type="primary" icon="plus" @click="handleAddProject">添加工程项目</a-button>
          </div>
          
          <a-table
            ref="projectTable"
            size="middle"
            bordered
            rowKey="id"
            :columns="projectColumns"
            :dataSource="projectList"
            :pagination="projectPagination"
            :loading="projectLoading"
            :scroll="{x: 'max-content'}"
            class="j-table-force-nowrap"
            @change="handleProjectTableChange">
            
            <template slot="statusSlot" slot-scope="text">
              <a-tag v-if="text == 0" color="blue">未开始</a-tag>
              <a-tag v-else-if="text == 1" color="green">进行中</a-tag>
              <a-tag v-else-if="text == 2" color="orange">已完成</a-tag>
            </template>
            
            <span slot="action" slot-scope="text, record">
              <a @click="handleEditProject(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteProject(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </a-table>
        </a-tab-pane>
        
        <a-tab-pane tab="备注信息" key="5">
          <a-form :form="form">
            <a-row>
              <a-col :span="24">
                <a-form-item label="备注" :labelCol="{span: 3}" :wrapperCol="{span: 19}">
                  <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="6" :disabled="true"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    
    <!-- 项目编辑表单 -->
    <project-modal ref="projectModal" @ok="handleProjectModalOk"></project-modal>
  </j-modal>
</template>

<script>
  import { getAction } from '@/api/manage'
  import { projectDelete, projectByCustomer } from '@/api/crm'
  import JAreaLinkage from '@/components/jeecg/JAreaLinkage'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import ProjectModal from './ProjectModal.vue'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import '@/assets/less/TableExpand.less'

  export default {
    name: "CustomerDetailModal",
    components: {
      JAreaLinkage,
      JDictSelectTag,
      JSelectUserByDep,
      ProjectModal
    },
    data() {
      return {
        title: "客户详情",
        width: 1000,
        visible: false,
        model: {},
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          customerName: { 
            rules: [{ required: true, message: '请输入客户名称!' }] 
          }
        },
        projectColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '项目名称',
            align:"center",
            dataIndex: 'projectName',
            width: 150
          },
          {
            title: '联系人',
            align:"center",
            dataIndex: 'contactPerson',
            width: 100
          },
          {
            title: '联系电话',
            align:"center",
            dataIndex: 'contactPhone',
            width: 120
          },
          {
            title: '项目状态',
            align:"center",
            dataIndex: 'status',
            width: 100,
            scopedSlots: { customRender: 'statusSlot' }
          },
          {
            title: '项目金额',
            align:"center",
            dataIndex: 'projectAmount',
            width: 120
          },
          {
            title: '开始日期',
            align:"center",
            dataIndex: 'startDate',
            width: 120
          },
          {
            title: '结束日期',
            align:"center",
            dataIndex: 'endDate',
            width: 120
          },
          {
            title: '省市区',
            align:"center",
            dataIndex: 'area',
            width: 180,
            customRender: (text, record) => {
              return this.renderArea(text, record);
            }
          },
          {
            title: '详细地址',
            align:"center",
            dataIndex: 'address',
            width: 200
          },
          {
            title: '项目描述',
            align:"center",
            dataIndex: 'description',
            width: 200,
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed: 'right',
            width: 120,
            scopedSlots: { customRender: 'action' }
          }
        ],
        projectList: [],
        projectLoading: false,
        projectPagination: {
          current: 1,
          pageSize: 10,
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条";
          },
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30', '40', '50']
        }
      }
    },
    mounted() {
      // 确保加载了地区数据
      if (!this.$Jpcaa) {
        console.warn('地区数据未加载，可能会影响省市区显示');
      }
    },
    methods: {
      // 预处理省市区数据，确保区域信息完整
      preprocessAreaData(record) {
        if (!record || !this.$Jpcaa) return record;
        
        // 如果有省市区编码但没有对应的名称，尝试从编码获取名称
        if (record.provinceCode && !record.provinceName && this.$Jpcaa['86']) {
          record.provinceName = this.$Jpcaa['86'][record.provinceCode] || '';
        }
        
        if (record.provinceCode && record.cityCode && !record.cityName && this.$Jpcaa[record.provinceCode]) {
          try {
            record.cityName = this.$Jpcaa[record.provinceCode][record.cityCode] || '';
          } catch (e) {
            console.error('获取城市名称失败:', e);
          }
        }
        
        if (record.provinceCode && record.cityCode && record.areaCode && !record.areaName) {
          try {
            // 特殊处理辽宁省鞍山市铁西区
            if (record.provinceCode === '210000' && record.cityCode === '210300' && record.areaCode === '210303') {
              record.areaName = '铁西区';
            } 
            // 尝试从$Jpcaa获取区域名称
            else if (this.$Jpcaa[record.provinceCode] && 
                typeof this.$Jpcaa[record.provinceCode][record.cityCode] === 'object') {
              record.areaName = this.$Jpcaa[record.provinceCode][record.cityCode][record.areaCode] || '';
            }
          } catch (e) {
            console.error('获取区域名称失败:', e);
          }
        }
        
        return record;
      },
      show(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        
        // 处理省市区数据
        if (record.provinceCode) {
          this.model.area = [record.provinceCode, record.cityCode, record.areaCode];
        }
        
        // 处理日期
        if (record.birthday) {
          this.model.birthday = moment(record.birthday);
        }
        
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 
            'customerName', 'customerCode', 'customerType', 'industry', 'customerSource', 'creditRating',
            'followUpStatus', 'followUpPerson', 'contactPerson', 'position', 'contactPhone', 'mobilePhone',
            'email', 'socialContact', 'gender', 'birthday', 'bankName', 'bankBranch', 'bankAccount',
            'accountName', 'taxNumber', 'invoiceTitle', 'creditLimit', 'paymentTerm', 'address', 'remark', 'area'))
        });
        
        // 加载客户项目列表
        this.loadProjectList();
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      handleOk() {
        this.close();
      },
      handleCancel() {
        this.close();
      },
      // 加载客户的工程项目列表
      loadProjectList() {
        if (!this.model.id) return;
        
        this.projectLoading = true;
        projectByCustomer({ 
          customerId: this.model.id
        }).then((res) => {
          if (res.success) {
            this.projectList = res.result || [];
            
            // 处理每个项目的省市区信息，确保数据完整
            if (this.projectList && this.projectList.length > 0) {
              this.projectList = this.projectList.map(project => this.preprocessAreaData(project));
            }
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.projectLoading = false;
        });
      },
      handleProjectTableChange(pagination) {
        this.projectPagination.current = pagination.current;
        this.projectPagination.pageSize = pagination.pageSize;
        this.loadProjectList();
      },
      // 添加工程项目
      handleAddProject() {
        this.$refs.projectModal.add();
        this.$refs.projectModal.title = "添加工程项目";
        this.$refs.projectModal.customerId = this.model.id;
        this.$refs.projectModal.customerName = this.model.customerName;
      },
      // 编辑工程项目
      handleEditProject(record) {
        this.$refs.projectModal.edit(record);
        this.$refs.projectModal.title = "编辑工程项目";
      },
      // 删除工程项目
      handleDeleteProject(id) {
        projectDelete({ id: id }).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadProjectList();
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      // 项目表单提交回调
      handleProjectModalOk() {
        this.loadProjectList();
      },
      formatAreaText() {
        let areas = [];
        if (this.model.provinceName) {
          areas.push(this.model.provinceName);
        }
        if (this.model.cityName) {
          areas.push(this.model.cityName);
        }
        if (this.model.areaName) {
          areas.push(this.model.areaName);
        }
        return areas.join(' / ');
      },
      // 省市区列的自定义渲染函数
      renderArea(text, record) {
        // 直接使用已保存的省市区名称显示
        let areaText = [];
        
        // 优先使用名称
        if (record.provinceName) areaText.push(record.provinceName);
        if (record.cityName && record.cityName !== '市辖区') areaText.push(record.cityName);
        if (record.areaName) areaText.push(record.areaName);
        
        // 如果没有名称，则显示编码
        if (areaText.length === 0) {
          if (record.provinceCode) areaText.push(record.provinceCode);
          if (record.cityCode) areaText.push(record.cityCode);
          if (record.areaCode) areaText.push(record.areaCode);
        }
        
        return areaText.length > 0 ? areaText.join('/') : '未设置';
      }
    }
  }
</script>

<style scoped>
/* 表格横向滚动样式 */
.ant-table-wrapper {
  overflow-x: auto;
}
.ant-table-body {
  overflow-x: auto !important;
}
/* 适配小屏幕设备 */
@media screen and (max-width: 1200px) {
  .ant-table-content {
    overflow-x: auto;
  }
}
</style> 